package com.aizuda.boot.modules.auth.controller;

import cn.hutool.json.JSONUtil;
import com.aizuda.boot.config.properties.FeiShuConfigProperties;
import com.aizuda.boot.modules.auth.service.IAuthService;
import com.aizuda.core.api.ApiAssert;
import com.aizuda.core.api.ApiController;
import com.aizuda.core.api.ApiResult;
import com.baomidou.kisso.annotation.LoginIgnore;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthFeishuRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

/**
 * @author hjw
 * @description oauth登录
 * @date 2025年06月24日 13:38
 */
@Tag(name = "飞书登录授权")
@RestController
@RequestMapping("/oauth")
@Slf4j
public class FeiShuAuthController extends ApiController {

    @Autowired
    private IAuthService authService;

    @Autowired
    private FeiShuConfigProperties feiShuConfigProperties;


    @Operation(summary = "获取飞书授权地址")
    @GetMapping("/render/{displayId}")
    @LoginIgnore
    public ApiResult<String> renderAuth(@Parameter(name = "飞书企业唯一标识") @PathVariable String displayId) throws IOException {
        log.info("进入 飞书 授权登录流程");
        AuthRequest authRequest = getAuthRequest(displayId);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.info("授权地址:{}", authorizeUrl);
        return ApiResult.ok(authorizeUrl);
    }

    /**
     * 授权回调
     *
     * @return 返回登录结果
     */
    @Operation(summary = "飞书授权登录回调")
    @GetMapping("/callback")
    @LoginIgnore
    public Map<String, Object> login(
            @Parameter(description = "授权码", required = true)
            @RequestParam(name = "code")
            String code,
            @RequestParam(name = "state")
            @Parameter(description = "状态值", required = true)
            String state,
            @Parameter(name = "displayId")
            @RequestParam(name = "displayId", required = true)
            String displayId
    ) {
        AuthCallback callback = AuthCallback.builder()
                .code(code)
                .state(state)
                .build();
        log.info("进入 飞书 授权登录回调流程");
        log.info("回调参数: {}", JSONUtil.toJsonStr(callback));
        AuthRequest authRequest = getAuthRequest(displayId);
        AuthResponse<AuthUser> callbackResponse = authRequest.login(callback);
        log.info("登录结果: {}", JSONUtil.toJsonStr(callbackResponse));
        ApiAssert.fail(!callbackResponse.ok(), "登录失败: " + callbackResponse.getMsg());

        AuthUser authUser = callbackResponse.getData();
        log.info("登录用户信息: {}", JSONUtil.toJsonStr(authUser));
        // 调用业务层处理登录逻辑
        return authService.feiShuLogin(authUser, request, response);
    }

    /**
     * 获取飞书授权请求
     *
     * @param displayId 企业编号
     * @return AuthRequest
     */
    private AuthRequest getAuthRequest(String displayId) {

        //根据不同的企业编号获取不同的配置信息
        FeiShuConfigProperties.FeiShuAppConfig feiShuAppConfig = feiShuConfigProperties.getApps().get(displayId);
        ApiAssert.fail(feiShuAppConfig == null, "当前企业{" + displayId + "}下飞书应用配置不存在，请检查配置文件");

        return new AuthFeishuRequest(AuthConfig.builder()
                .clientId(feiShuAppConfig.getAppId())
                .clientSecret(feiShuAppConfig.getAppSecret())
                .redirectUri(feiShuAppConfig.getRedirectUri())
                .build());
    }
}
